package com.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.text.Position;

import model.CompensationLeaveDTO;
import model.PositionDTO;
import model.UserDTO;

import org.apache.log4j.Logger;

import dao.mysql.MySqlImpl;

import util.IdGenerator;
import util.Validation;
import bizlogic.CompensationLeaveManager;
import bizlogic.PositionManager;
import bizlogic.UserManager;
import exception.DAOSystemException;

/**
 * @Pranjal
 * Servlet implementation class UserEdit
 */

public class UserEdit extends HttpServlet {
	/**
	 * @pranjal
	 */
	private static final long serialVersionUID = 4827014212728524042L;

	private Logger logger = Logger.getLogger(this.getClass());
	private RequestDispatcher usereditJsp;

	@Override
	public void init(ServletConfig config) throws ServletException {
		ServletContext context = config.getServletContext();
		usereditJsp = context.getRequestDispatcher("/admin-user.jsp");
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

			//doAdd(req);
			doGet(req, resp);

	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = null;

			String validation= Validation.validate(req,resp);
			
				if(req.getParameter("action") != null)
					action = (String) req.getParameter("action").trim();
				
				if (action != null && validation=="ERROR:") {
					logger.debug("HomeServlet.doProcess()");
					if (action.equals("delete")) {
						doDelete(req);
						req.setAttribute("state", "delete");	
						doRefresh(req, resp);
					}
					else if (action.equals("add")) {
						doAdd(req);
						req.setAttribute("state", "add");	
						doRefresh(req, resp);
					}
					else if (action.equals("initupdate")) {
						logger.debug("HomeServlet.doInitUpdate()");
						req.setAttribute("state", "initupdate");	
						doInitUpdate(req);
						doRefresh(req, resp);
					}
					else if (action.equals("update")) {
						logger.debug("HomeServlet.doUpdate()");
						req.setAttribute("state", "update");	
						doUpdate(req);
						doRefresh(req, resp);
					}
				}
				else if (validation!="ERROR:")
				{
					for (String name : Collections.list((Enumeration<String>)req.getParameterNames()))
					{
						Object o = req.getAttribute(name);
						if(o!=null)
						{
							req.setAttribute(name, o);
							System.out.println(name);
						}
					}
					req.setAttribute("msg", validation);
					req.setAttribute("state", "invalid");
					doRefresh(req, resp);
				}
				else
				{
					req.setAttribute("state", "none");
					doRefresh(req, resp);
				}
			
	}

	private void doUpdate(HttpServletRequest req) {
		String id = req.getParameter("id");
		try
		{
			UserDTO user = new UserDTO();
			
			System.out.println(req.getParameter("id"));
			user.setId(id);
			
			System.out.println(req.getParameter("name").trim());
			user.setName(req.getParameter("name"));
			
			System.out.println(req.getParameter("username").trim());
			user.setUserName(req.getParameter("username"));
			
			System.out.println(req.getParameter("password").trim());
			user.setPassword(req.getParameter("password"));
			
			System.out.println(req.getParameter("address").trim());
			user.setAddress(req.getParameter("address"));
			
			System.out.println(req.getParameter("email").trim());
			user.setEmail(req.getParameter("email"));

			System.out.println(req.getParameter("phone").trim());
			user.setPhoneNumber(Integer.valueOf(
					req.getParameter("phone").trim()).intValue());
			
			PositionManager posman = new PositionManager();
			System.out.println(req.getParameter("posId").trim());
			PositionDTO p = posman.findPosition(req.getParameter("posId").trim());
			user.setPosition(p);
			
			UserManager useman = new UserManager();
			System.out.println(req.getParameter("mgrId").trim());
			UserDTO mgr = useman.findUser(req.getParameter("mgrId").trim());
			user.setManager(mgr);
			
			System.out.println(req.getParameter("ca1").trim());
			user.setConsumeAnnualAllowance(Double.valueOf(
					req.getParameter("ca1").trim()).doubleValue());
			
			System.out.println(req.getParameter("cm1").trim());
			user.setConsumeAnnualAllowance(Double.valueOf(
					req.getParameter("cm1").trim()).doubleValue());
			
			UserManager userman = new UserManager();
			userman.updateUser(user);
			String msg = "Updated: " + id;
			req.setAttribute("msg", msg);
		}
		catch(DAOSystemException e)
		{
			String msg = "Update Failed: " + e.getShortMessage();
			req.setAttribute("msg", msg);
		}
	}

	private void doInitUpdate(HttpServletRequest req) {
			logger.debug("HomeServlet.doInitUpdate()");
			String id = req.getParameter("id");
			UserManager posman = new UserManager();
			UserDTO pos;
			try {
				pos = posman.findUser(id);
				req.setAttribute("id", pos.getId());
				req.setAttribute("name", pos.getName());
				req.setAttribute("username", pos.getUserName());
				req.setAttribute("password", pos.getPassword());
				req.setAttribute("address", pos.getAddress());
				req.setAttribute("email", pos.getEmail());
				req.setAttribute("phone", pos.getPhoneNumber());
				req.setAttribute("posId", pos.getPosition().getId());
				req.setAttribute("mgrId", pos.getManager().getId());
				req.setAttribute("ca1", pos.getConsumeAnnualAllowance());
				req.setAttribute("cm1", pos.getConsumeMedicalAllowance());
			} catch (DAOSystemException e) {
				String msg = "Cannot Update: " + e.getShortMessage();
				req.setAttribute("msg", msg);
			}
	}

	private void doDelete(HttpServletRequest req) {
		String id = req.getParameter("id");
		UserManager posman = new UserManager();
		try {
			posman.deleteUser(posman.findUser(id));
			
			CompensationLeaveManager compman = new CompensationLeaveManager();
			CompensationLeaveDTO cm = compman.findCompensationLeave(id);
			
			if(cm != null)
				compman.deleteCompensationLeave(cm);
			
		} catch (Exception e) {
/*			String msg1 = "DELETE FAILED: " + e.getShortMessage();
			req.setAttribute("msg1", msg1);	*/
		}
		String msg1 = "DELETED: " + id;
		req.setAttribute("msg1", msg1);		
	}
	
	private void doAdd(HttpServletRequest req) {
		try
		{
			String id = IdGenerator.generateUserID().toString();
			if(id.length()!=3)
				if(id.length()!=2)
					id="00"+id;
				else
					id="0"+id;
			
			String name = req.getParameter("name").trim();
			String username = req.getParameter("username").trim();
			String password = req.getParameter("password").trim();
			String address = req.getParameter("address").trim();
			String email = req.getParameter("email").trim();
			int phone = Double.valueOf(req.getParameter("phone").trim()).intValue();
			String pos = req.getParameter("posId").trim();
			String mgr =req.getParameter("mgrId").trim();
			
			if(mgr.length()!=3)
				if(mgr.length()!=2)
					mgr="00"+mgr;
				else
					mgr="0"+mgr;
					
			double ca1 = Double.valueOf(
					req.getParameter("ca1").trim()).doubleValue();	
			double cm1 =Double.valueOf(
					req.getParameter("cm1").trim()).doubleValue();
			
		 	String insertSql = "INSERT INTO user VALUES('" 
				 + id
				 + "', '" + name 
				 + "', '" + username
				 + "', '" + password
				 + "', '" + address
				 + "', '" + email
				 + "', '" + phone
				 + "', '" + pos
				 + "', '" + mgr
				 + "', '" + ca1
				 + "', '" + cm1
				 + "');";
		 	System.out.println(insertSql);
		 	//directInsertUser(insertSql);// trying a hack as insert is failing due to FK constraint
	 	
			new UserManager().insertUser(new UserDTO(id,name, username, password , address, email, phone , new PositionDTO(pos), new UserDTO(mgr) , ca1, cm1));
			new CompensationLeaveManager().insertCompensationLeave(new CompensationLeaveDTO(id,0,0,0));//create new comp leave
			String msg = "ADDED ";
			req.setAttribute("msg", msg);
		}
		catch(DAOSystemException e)
		{
			String msg = "Add Failed: " + e.getShortMessage();
			req.setAttribute("msg", msg);
		}
	}

/*	private void directInsertUser(String insertSql) throws DAOSystemException
	{
		MySqlImpl mysqlImpl = new MySqlImpl();
        try {
            int res = mysqlImpl.execute(insertSql);
           
        } catch (Exception e) {
            String error = "Error inserting users. Nested Exception is: " + e;
            System.out.println(error);
            throw new DAOSystemException(error);
        } finally {
            try {
                mysqlImpl.close();
            } catch (Exception e) {
            }
        }
	}*/
	
	
	protected void doRefresh(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		UserManager userman = new UserManager();
		ArrayList<UserDTO> posList = new ArrayList<UserDTO>();
		System.out.print(posList.toString());

		try {
			posList = userman.findAllUser();
		} catch (DAOSystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		logger.debug("HomeServlet.doRefresh()");
		req.setAttribute("posList", posList);
		usereditJsp.forward(req, resp);
	}

}
